import {
  AutoComplete,
  Cascader,
  Form,
  Input,
  InputNumber,
  Modal,
  notification,
  Radio,
  TreeSelect,
} from 'antd';
import { useEffect, useState } from 'react';

import menuService, { MenuForm } from '@/api/services/security/menuService';
import { pagesSelect } from '@/router/hooks/use-permission-routes';
import { useOperation } from '@/store/userStore';
import { hasPermission } from '@/utils/permission';

// eslint-disable-next-line import/namespace
import { Menu } from '#/entity';
import { BasicStatus, MenuType } from '#/enum';

export type MenuModalProps = {
  formValue: Menu;
  menus: Menu[];
  title: string;
  show: boolean;
  onOk: VoidFunction;
  onCancel: VoidFunction;
};

// eslint-disable-next-line func-names
export default function ({ title, menus, show, formValue, onOk, onCancel }: MenuModalProps) {
  const operations = useOperation();
  const [form] = Form.useForm();
  const [compOptions, setCompOptions] = useState(pagesSelect);
  const updateCompOptions = (name: string) => {
    setCompOptions(
      pagesSelect.filter((path) => {
        return path.value.includes(name.toLowerCase());
      }),
    );
  };

  useEffect(() => {
    form.setFieldsValue({ ...formValue });
    form.setFieldValue('parentId', formValue.parent?.id);
    form.setFieldValue('operationPkForm', formValue.operationArray);
  }, [formValue, form]);

  const onFinish = (values: any) => {
    // console.log(values.operationPkForm);
    if (values.operationPkForm) {
      values.operationPkForm = {
        code: values.operationPkForm[2],
        entity: { entity: values.operationPkForm[1], module: values.operationPkForm[0] },
      };
    } else if (formValue.operationArray) {
      if (!formValue.id) {
        values.operationPkForm = {
          code: formValue.operationArray![2],
          entity: { entity: formValue.operationArray![1], module: formValue.operationArray![0] },
        };
      }
    }
    if (!values.parentId) {
      if (!formValue.id) {
        values.parentId = formValue.parent?.id;
      }
    }

    if (formValue.id) {
      menuService.updateMenu(formValue.id!, values).then(() => {
        notification.success({ message: '修改成功' });
        onOk();
      });
    } else {
      menuService.createMenu(values).then(() => {
        notification.success({ message: '新增成功' });
        onOk();
      });
    }
  };

  return (
    <Modal
      title={title}
      open={show}
      onCancel={onCancel}
      okButtonProps={{
        autoFocus: true,
        htmlType: 'submit',
        disabled: !hasPermission('SECURITY:MENU:UPDATE') && formValue.id === undefined,
      }}
      destroyOnClose
      modalRender={(dom) => (
        <Form
          initialValues={formValue}
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          onFinish={onFinish}
          clearOnDestroy
          layout="horizontal"
        >
          {dom}
        </Form>
      )}
    >
      <Form.Item<MenuForm> label="类型" name="type" rules={[{ required: true }]}>
        <Radio.Group optionType="button" buttonStyle="solid">
          <Radio value={MenuType.CATALOGUE}>目录</Radio>
          <Radio value={MenuType.MENU}>菜单</Radio>
          <Radio value={MenuType.BUTTON}>按钮</Radio>
        </Radio.Group>
      </Form.Item>

      <Form.Item<MenuForm> label="名称" name="name" rules={[{ required: true }]}>
        <Input />
      </Form.Item>

      <Form.Item<MenuForm> label="父级菜单" name="parentId">
        <TreeSelect
          fieldNames={{
            label: 'name',
            value: 'id',
            children: 'children',
          }}
          allowClear
          treeData={menus}
          popupMatchSelectWidth={false}
          defaultValue={formValue.parent?.id}
          onChange={(_value, labelList) => {
            updateCompOptions(labelList[0] as string);
          }}
        />
      </Form.Item>

      <Form.Item<MenuForm> label="路由" name="route" rules={[{ required: true }]}>
        <Input />
      </Form.Item>

      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}
      >
        {({ getFieldValue }) => {
          if (getFieldValue('type') === MenuType.MENU) {
            return (
              <Form.Item<MenuForm>
                label="组件地址"
                name="component"
                required={getFieldValue('type') === MenuType.MENU}
              >
                <AutoComplete
                  options={compOptions}
                  filterOption={(input, option) =>
                    ((option?.label || '') as string).toLowerCase().includes(input.toLowerCase())
                  }
                />
              </Form.Item>
            );
          }
          return null;
        }}
      </Form.Item>

      <Form.Item<MenuForm> label="权限标识" name="operationPkForm">
        <Cascader defaultValue={formValue.operationArray} options={operations} changeOnSelect />
      </Form.Item>

      <Form.Item<MenuForm> label="图标" name="icon" tooltip="local icon should start with ic">
        <Input />
      </Form.Item>

      <Form.Item<MenuForm> label="排序" name="sort" rules={[{ required: true }]}>
        <InputNumber />
      </Form.Item>

      <Form.Item<MenuForm> label="是否隐藏" name="hidden" tooltip="hide in menu">
        <Radio.Group optionType="button" buttonStyle="solid">
          <Radio value={false}>展示</Radio>
          <Radio value>隐藏</Radio>
        </Radio.Group>
      </Form.Item>

      <Form.Item<MenuForm> label="状态" name="status" required>
        <Radio.Group optionType="button" buttonStyle="solid">
          <Radio value={BasicStatus.ENABLE}> 启用 </Radio>
          <Radio value={BasicStatus.DISABLE}> 禁用 </Radio>
        </Radio.Group>
      </Form.Item>
    </Modal>
  );
}
